package com.jic.purchase.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.store.MStoreApi;
import com.jic.product.store.request.MStoreShopSyncStockRequest;
import com.jic.purchase.constant.consist.ResponseCode;
import com.jic.purchase.model.entity.PurchaseOrder;
import com.jic.purchase.service.PurchaseOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;
import com.github.pagehelper.PageInfo;

import java.util.List;
import java.util.stream.Collectors;

import com.jic.common.base.vo.RestResult;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import com.jic.purchase.model.vo.request.PurchaseContractProductRelRequest;
import com.jic.purchase.model.vo.response.PurchaseContractProductRelResponse;
import com.jic.purchase.model.entity.PurchaseContractProductRel;
import com.jic.purchase.service.PurchaseContractProductRelService;

import javax.annotation.Resource;

/**
 * @Author: 建投数据科技(山东)有限公司
 * @date: 2020-06-03 14:17:40
 */
@RestController
@Slf4j
@RequestMapping("/purchaseContractProductRel")
@Api(tags = " [合同和商品的关联表]控制类-PC")
public class PurchaseContractProductRelController {
    @Autowired
    private PurchaseContractProductRelService service;

    @Resource
    private MStoreApi mStoreApi;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    /**
     * 新增记录
     *
     * @param request 新增[合同和商品的关联表]请求参数
     * @return PurchaseContractProductRelResponse 新增[合同和商品的关联表]响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "新增[合同和商品的关联表]记录")
    @PostMapping("/save")
    @ResponseBody
    public RestResult<Long> save(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        long flag = service.save(purchaseContractProductRel);
        return RestResult.success(flag);
    }

    @PostMapping("/deleteByContractCode")
    @ResponseBody
    public RestResult<Long> deleteByContractCode(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        service.deleteByContractCode(purchaseContractProductRel);
        return RestResult.success(1L);
    }

    /**
     * 新增或修改记录
     *
     * @param request 新增或修改[合同和商品的关联表]请求参数
     * @return PurchaseContractProductRelResponse 新增或修改[合同和商品的关联表]响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "保存或更新[合同和商品的关联表]")
    @PostMapping("/saveOrUpdate")
    @ResponseBody
    public RestResult<Long> saveOrUpdate(@Validated @RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        long flag = service.saveOrUpdate(purchaseContractProductRel);
        return RestResult.success(flag);
    }

    /**
     * 删除记录
     *
     * @param request 删除[合同和商品的关联表]请求参数
     * @return PurchaseContractProductRelResponse 删除[合同和商品的关联表]响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "删除[合同和商品的关联表]记录")
    @PostMapping("/delete")
    @ResponseBody
    public RestResult<Long> delete(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        long flag = service.deleteByPrimaryKey(purchaseContractProductRel);
        return RestResult.success(flag);
    }

    /**
     * 修改记录
     *
     * @param request 修改[合同和商品的关联表]请求参数
     * @return PurchaseContractProductRelResponse 修改[合同和商品的关联表]响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "修改[合同和商品的关联表]记录")
    @PostMapping("/update")
    @ResponseBody
    public RestResult<Long> update(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        long flag = service.updateByPrimaryKeySelective(purchaseContractProductRel);
        return RestResult.success(flag);
    }

    /**
     * 修改记录
     *
     * @param request 修改[合同和商品的关联表]请求参数
     * @return PurchaseContractProductRelResponse 修改[合同和商品的关联表]响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "修改[合同和商品的关联表]记录")
    @PostMapping("/updatenum")
    @ResponseBody
    public RestResult<Long> updatenum(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, purchaseContractProductRel);
        JSONArray ja = JSONArray.fromObject(request.getArrs());
        JSONArray j = JSONArray.fromObject(request.getArr());
        long flag = 0;
        if (ja.getJSONObject(0).size() != 0) {
            //收货
            Boolean overFlag = true;
            for (int i = 0; i < ja.size(); i++) {
                purchaseContractProductRel.setId(Long.parseLong(ja.getJSONObject(i).get("ID").toString()));
                purchaseContractProductRel.setRealRecievedNum(Integer.parseInt(ja.getJSONObject(i).get("value").toString()));
                //更新对应商品收货数量
                flag = service.updateByPrimaryKeySelective(purchaseContractProductRel);
                //更新对应库存
                MStoreShopSyncStockRequest syncStockRequest = new MStoreShopSyncStockRequest();
                syncStockRequest.setStoreName("1");
                syncStockRequest.setProductBarNo("1");
                syncStockRequest.setProductCode("1");
                syncStockRequest.setProductName("1");
                //todo 实际入库数量不是收货数量
                syncStockRequest.setRealRecievedNum(1);
                syncStockRequest.setStoreCode("1");
                mStoreApi.syncStock(syncStockRequest);

                //根据id查询商品采购数量对比实际收货数量判断是否全部收货完成
                purchaseContractProductRel.setRealRecievedNum(null);
                List<PurchaseContractProductRel> relList = service.listAllRecord(purchaseContractProductRel);
                if (CollectionUtil.isNotEmpty(relList)) {
                    PurchaseContractProductRel productRel = relList.get(0);
                    if (productRel.getPurchaseNum() > Integer.parseInt(ja.getJSONObject(i).get("value").toString())) {
                        overFlag = false;
                    }
                }
            }
            if (overFlag) {
                //更新采购单状态为收货完成
                PurchaseContractProductRel productRel = new PurchaseContractProductRel();
                productRel.setId(Long.parseLong(ja.getJSONObject(0).get("ID").toString()));
                List<PurchaseContractProductRel> productRels = service.listAllRecord(productRel);
                PurchaseOrder order = new PurchaseOrder();
                //TODO
                order.setContractId(productRels.get(0).getContractCode());
                order.setType(1);
                List<PurchaseOrder> orders = purchaseOrderService.listAllRecord(order);
                order.setId(orders.get(0).getId());
                order.setStatus(5);
                purchaseOrderService.updateByPrimaryKeySelective(order);
            }

        } else {
            //发货
            Boolean overFlag = true;
            for (int i = 0; i < j.size(); i++) {
                purchaseContractProductRel.setId(Long.parseLong(j.getJSONObject(i).get("ID").toString()));
                purchaseContractProductRel.setRealDeliveryNum(Integer.parseInt(j.getJSONObject(i).get("value").toString()));
                flag = service.updateByPrimaryKeySelective(purchaseContractProductRel);
                //根据id查询商品采购数量对比实际发货数量判断是否全部发货完成
                purchaseContractProductRel.setRealRecievedNum(null);
                List<PurchaseContractProductRel> relList = service.listAllRecord(purchaseContractProductRel);
                if (CollectionUtil.isNotEmpty(relList)) {
                    PurchaseContractProductRel productRel = relList.get(0);
                    if (productRel.getPurchaseNum() > Integer.parseInt(j.getJSONObject(i).get("value").toString())) {
                        overFlag = false;
                    }
                }
            }
            if (overFlag) {
                //更新采购单状态为发货完成
                PurchaseContractProductRel productRel = new PurchaseContractProductRel();
                productRel.setId(Long.parseLong(j.getJSONObject(0).get("ID").toString()));
                List<PurchaseContractProductRel> productRels = service.listAllRecord(productRel);
                PurchaseOrder order = new PurchaseOrder();
                //TODO
                order.setContractId(productRels.get(0).getContractCode());
                order.setType(1);
                List<PurchaseOrder> orders = purchaseOrderService.listAllRecord(order);
                order.setId(orders.get(0).getId());
                order.setStatus(4);
                purchaseOrderService.updateByPrimaryKeySelective(order);
            }
        }
        return RestResult.success(flag);
    }


    @PostMapping("/returnOrderOperate")
    @ApiOperation(value = " 退货单减库存 ")
    @ResponseBody
    public RestResult<Boolean> returnOrderOperate(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        Boolean flag = service.returnOrderOperate(request);
        return RestResult.success(flag);
    }

    @PostMapping("/addOrderOperate")
    @ApiOperation(value = " 补货单加库存 ")
    @ResponseBody
    public RestResult<Boolean> addrderOperate(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        Boolean flag = service.addOrderOperate(request);
        return RestResult.success(flag);
    }

    /**
     * 单表查询详情信息
     *
     * @param request 查询[合同和商品的关联表]详情请求参数
     * @return PurchaseContractProductRelResponse 查询[合同和商品的关联表]详情响应参数
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:04
     */
    @PostMapping("/getByPrimaryKey")
    @ApiOperation(value = "查询[合同和商品的关联表]详情")
    @ResponseBody
    public RestResult<PurchaseContractProductRelResponse> getByPrimaryKey(@Validated @RequestBody PurchaseContractProductRelRequest request) {
        log.info("查询详情请求参数入参，{}", JSONObject.toJSONString(request));
        if (request != null && request.getId() != null) {

            PurchaseContractProductRel purchaseContractProductRel = new PurchaseContractProductRel();
            BeanUtils.copyProperties(request, purchaseContractProductRel);
            PurchaseContractProductRel result = service.getByPrimaryKey(purchaseContractProductRel);
            log.info("查询详情请求参数出参，{}", JSONObject.toJSONString(result));
            if (result == null) {
                return RestResult.error(ResponseCode.EXCEPTION, "记录不存在");
            }
            PurchaseContractProductRelResponse bo = new PurchaseContractProductRelResponse();
            BeanUtils.copyProperties(result, bo);
            return RestResult.success(bo);
        }
        log.info("查询详情请求结束");
        return RestResult.success(new PurchaseContractProductRelResponse());
    }

    /**
     * 分页查询
     *
     * @param request 分页查询请求参数
     * @return 分页列表
     * @throws Throwable 业务异常和系统异常
     */
    @PostMapping("/listPage")
    @ApiOperation(value = " 分页查询列表 ")
    @ResponseBody
    public RestResult<PageInfo<PurchaseContractProductRel>> listPage(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel param = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        return RestResult.success(service.listPageBySelective(param, request.getPageNum(), request.getPageSize()));
    }

    /**
     * PURCHASE_CONTRACT_PRODUCT_REL 查询列表（不分页）
     *
     * @param request 前端请求参数
     */
    @PostMapping("/listAll")
    @ApiOperation(value = "不分页查询 [合同和商品的关联表] ")
    @ResponseBody
    public RestResult<List<PurchaseContractProductRelResponse>> listPurchaseContractProductRelAllRecord(@RequestBody PurchaseContractProductRelRequest request) throws Throwable {
        PurchaseContractProductRel param = new PurchaseContractProductRel();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        List<PurchaseContractProductRel> list = service.listAllRecord(param);
        List<PurchaseContractProductRelResponse> responseList = list.stream().map(temp -> {
            PurchaseContractProductRelResponse bo = new PurchaseContractProductRelResponse();
            BeanUtils.copyProperties(temp, bo);
            return bo;
        }).filter(item -> item != null).collect(Collectors.toList());
        return RestResult.success(responseList);
    }

}

